<script setup>
import { ref, onMounted } from 'vue'
import FromDrawer from '@/components/from-drawer.vue'
import { toast } from '@/utils/elnotification'
import {
  getRuleList,
  updateStatusApi,
  updateRuleInfoApi,
  deleteRuleByIdApi,
  createRuleApi
} from '@/api/rule'
import ListHeader from '@/components/list-header.vue'
import IconSelect from '@/components/icon-select.vue'

//绑定表格数据
const tableData = ref([])
//总页数
const total = ref(0)
//当前页
const currentPage = ref(1)
//加载动画
const loading = ref(false)
//公告标题
const title1 = ref('')

//管理员列表
const rules = ref([])

//默认展开
const defaultExpandedkeys = ref([])

//获取表格数据
const getData = async (p = null) => {
  if (typeof p === 'number') {
    currentPage.value = p
  }
  loading.value = true
  try {
    const res = await getRuleList(currentPage.value)

    tableData.value = res.list.map((item) => {
      item.statusLoading = false
      return item
    })
    defaultExpandedkeys.value = res.list.map((item) => item.id)
    total.value = res.totalCount
    rules.value = res.rules
  } catch (error) {
  } finally {
    loading.value = false
  }
}

//删除
const onDelete = async (row) => {
  event.stopPropagation() //阻止事件冒泡
  fromDrawerRef.value.showLoading()
  try {
    await deleteRuleByIdApi(row)
    toast('删除成功')
    getData(1)
  } catch (error) {
    toast('仅供演示，来到此步表示操作成功', 'error')
  } finally {
    fromDrawerRef.value.hideLoading()
  }
}

//新增
const fromDrawerRef = ref(null)
const onAdd = () => {
  title1.value = '新增'
  fromDrawerRef.value.open()
  form.value = {
    rule_id: 0,
    menu: 0,
    name: '',
    condition: '',
    method: 'GET',
    status: 1,
    order: 50,
    icon: '',
    frontpath: ''
  }
}

//表单部分
const formRef = ref(null)
const form = ref({
  rule_id: 0,
  menu: 0,
  name: '',
  condition: '',
  method: 'GET',
  status: 1,
  order: 50,
  icon: '',
  frontpath: ''
})

//确认提交
const onSubmit = async () => {
  const val = await formRef.value.validate((val) => val)
  if (!val) return
  fromDrawerRef.value.showLoading()
  if (changId.value !== 0) {
    try {
      await updateRuleInfoApi(changId.value, { ...form.value })
      toast('编辑成功')
      getData(1)
    } catch (error) {
      toast('仅供演示，来到此步表示操作成功', 'error')
    } finally {
      fromDrawerRef.value.hideLoading()
    }
  } else {
    try {
      await createRuleApi({ ...form.value })
      toast('新增成功')
      getData(1)
    } catch (error) {
      toast('仅供演示，来到此步表示操作成功', 'error')
    } finally {
      fromDrawerRef.value.hideLoading()
    }
  }
}

//修改
const changId = ref(0)
const onChange = (row) => {
  title1.value = '修改信息'
  const { rule_id, menu, name, condition, method, status, order, icon } = row
  form.value = {
    rule_id,
    menu,
    name,
    condition,
    method,
    status,
    order,
    icon
  }
  changId.value = rule_id
  fromDrawerRef.value.open()
}

//修改状态
const onChangeStatus = async (status, row) => {
  row.statusLoading = true
  try {
    await updateStatusApi(row.id, status)
    toast('修改状态成功')
    row.status = status
  } catch (error) {
    toast('仅供演示，来到此步表示操作成功', 'error')
  } finally {
    row.statusLoading = false
  }
}

//添加子菜单
const addChild = (id) => {
  onAdd()
  form.value.rule_id = id
  form.value.status = 1
}

onMounted(() => {
  getData()
})
</script>

<template>
  <el-card shadow="never" class="border-0" v-loading="loading">
    <ListHeader @create="onAdd" @refresh="getData" :delete1="false"></ListHeader>
    <el-tree
      :data="tableData"
      :props="{ label: 'name', children: 'child' }"
      node-key="id"
      :default-expanded-keys="defaultExpandedkeys"
    >
      <template #default="{ node, data }">
        <div class="flex flex-1 items-center text-[14px] pr-[8px]">
          <el-tag size="small" :type="data.menu ? '' : 'info'">
            {{ data.menu ? '菜单' : '权限' }}
          </el-tag>
          <el-icon v-if="data.icon" :size="16" class="mx-4">
            <component :is="data.icon"></component>
          </el-icon>
          <span>{{ data.name }}</span>
          <div class="ml-auto">
            <span @click.stop="() => {}">
              <el-switch
                :modelValue="data.status"
                :active-value="1"
                :inactive-value="0"
                @change="onChangeStatus($event, data)"
              >
              </el-switch>
            </span>
            <el-button type="primary" size="small" text @click.stop="onChange(data)"
              >修改</el-button
            >
            <el-button type="primary" size="small" text @click.stop="addChild(data.id)"
              >增加</el-button
            >

            <span @click.stop="() => {}">
              <el-popconfirm
                title="是否要删除该菜单？"
                confirm-button-text="确认"
                cancel-button-text="取消"
                @confirm="onDelete(data.id)"
              >
                <template #reference>
                  <el-button type="primary" size="small" text>删除</el-button>
                </template>
              </el-popconfirm>
            </span>
          </div>
        </div>
      </template>
    </el-tree>
  </el-card>

  <div class="flex justify-center justify-center mt-5">
    <el-pagination
      @current-change="getData"
      :current-page="currentPage"
      background
      layout="prev,pager,next"
      :total="total"
    />
  </div>
  <FromDrawer ref="fromDrawerRef" :title="title1" @submit="onSubmit">
    <el-form :model="form" ref="formRef" label-width="80px" :inline="false">
      <el-form-item label="上级菜单" prop="rule_id">
        <el-cascader
          v-model="form.rule_id"
          :options="rules"
          :props="{
            value: 'id',
            label: 'name',
            children: 'child',
            checkStrictly: true,
            emitPath: false
          }"
          placeholder="请选择上级菜单"
        />
      </el-form-item>
      <el-form-item label="菜单/规则" prop="menu">
        <el-radio-group v-model="form.menu">
          <el-radio :label="1" size="large" border>菜单</el-radio>
          <el-radio :label="0" size="large" border>规则</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入名称"></el-input>
      </el-form-item>
      <el-form-item label="菜单图标" prop="icon" v-if="form.menu == 1">
        <IconSelect v-model="form.icon"></IconSelect>
      </el-form-item>
      <el-form-item label="前端路由" prop="frontpath" v-if="form.menu == 1 && form.rule_id > 0">
        <el-input v-model="form.frontpath" placeholder="请输入前端路由"></el-input>
      </el-form-item>
      <el-form-item label="后端规则" prop="condition" v-if="form.menu == 0">
        <el-input v-model="form.condition" placeholder="请输入后端规则"></el-input>
      </el-form-item>
      <el-form-item label="请求方式" prop="method" v-if="form.menu == 0">
        <el-select v-model="form.method" placeholder="请选择请求方式">
          <el-option
            v-for="item in ['GET', 'POST', 'PUT', 'DELETE']"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="order">
        <el-input-number v-model="form.order" :min="1" :max="10000" />
      </el-form-item>
    </el-form>
  </FromDrawer>
</template>

<style lang="less" scoped>
:deep(.el-tree-node__content) {
  padding: 20px 0;
}
</style>
